<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch"
             label-width="68px">
      <el-form-item label="标签名字" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入标签名字"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="删除标识" prop="delFlag">
        <el-select
          v-model="queryParams.delFlag"
          placeholder="请选择状态"
          clearable
          @change="handleQuery"
        >
          <el-option label="正常" :value="0"></el-option>
          <el-option label="已删除" :value="1"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['forum:label:add']"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['forum:label:edit']"
        >修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['forum:label:remove']"
        >删除
        </el-button>
      </el-col>

      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table 
      v-loading="loading" 
      :data="labelList" 
      row-key="id"
      :default-sort = "{prop: 'sortNum', order: 'descending'}"
    >
      <el-table-column label="话题标签id" align="center" prop="id"/>
      <el-table-column label="标签名字" align="center" prop="name"/>
      <el-table-column label="排序字段数字越大优先级越高" align="center" prop="sortNum" sortable>
        <template slot-scope="scope">
          <span>{{ scope.row.sortNum }}</span>
          <i class="el-icon-rank" style="margin-left: 5px; cursor: move;" title="拖拽排序"></i>
        </template>
      </el-table-column>
      <el-table-column label="创建人" align="center" prop="createBy"/>
      <el-table-column label="更新时间" align="center" prop="updateTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.updateTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="编辑人" align="center" prop="updateBy"/>
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            v-if="scope.row.delFlag == '0'"
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['forum:label:edit']"
          >修改
          </el-button>
          <el-button
            v-if="scope.row.delFlag == '0'"
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['forum:label:remove']"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改论坛话题对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="标签名字" prop="name">
          <el-input v-model="form.name" placeholder="请输入标签名字"/>
        </el-form-item>
        <el-form-item label="删除标识" prop="delFlag">
          <el-select v-model="form.delFlag" placeholder="请选择状态">
            <el-option label="正常" :value="0"></el-option>
            <el-option label="已删除" :value="1"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="排序值" prop="sortNum">
          <el-input-number v-model="form.sortNum" placeholder="请输入排序值 数字越大优先级越高"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {addLabel, delLabel, getLabel, listLabel, sortLabels} from "@/api/forum/label"
import Sortable from 'sortablejs'

export default {
  name: "TopicLabel",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 论坛话题表格数据
      labelList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: null,
        delFlag: 0,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        name: [
          {required: true, message: "标签名字不能为空", trigger: "blur"}
        ],
        delFlag: [
          {required: true, message: "请选择删除标识", trigger: "change"}
        ],
        sortNum: [
          {required: true, message: "排序值不能为空", trigger: "blur"}
        ]
      }
    }
  },
  created() {
    this.getList()
  },
  mounted() {
    this.setSort()
  },
  methods: {
    /** 查询论坛话题列表 */
    getList() {
      this.loading = true
      listLabel(this.queryParams).then(response => {
        this.labelList = response.rows
        this.total = response.total
        this.loading = false
        this.$nextTick(() => {
          this.setSort()
        })
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        name: null,
        createBy: null,
        delFlag: null,
        sortNum: null,
        id: null,
        updateTime: null,
        updateBy: null,
        createTime: null
      }
      this.resetForm("form")
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm")
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = "添加论坛话题"
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const id = row.id || this.ids
      getLabel(id).then(response => {
        this.form = response.data
        this.open = true
        this.title = "修改论坛话题"
      })
    },
    /** 提交按钮 */
    submitForm: function () {
      this.$refs["form"].validate(valid => {
        if (valid) {
          const formData = new FormData();
          formData.append('name', this.form.name);
          formData.append('delFlag', this.form.delFlag);
          formData.append('sort', this.form.sortNum);

          if (this.form.id !== undefined && this.form.id !== null) {
            formData.append('id', this.form.id);
          }

          addLabel(formData).then(response => {
            this.$modal.msgSuccess("成功")
            this.open = false
            this.getList()
          })
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      this.$modal.confirm('是否确认删除名称为"' + row.name + '"的数据项？').then(function () {
        return delLabel(row.id)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess("删除成功")
      }).catch(() => {
      })
    },
    /** 设置排序 */
    setSort() {
      const el = document.querySelector('.el-table__body-wrapper tbody')
      if (!el) return
      this.sortable = Sortable.create(el, {
        ghostClass: 'sortable-ghost',
        setData: function (dataTransfer) {
          dataTransfer.setData('Text', '')
        },
        onEnd: evt => {
          const { oldIndex, newIndex } = evt
          this.updateSortOrder(oldIndex, newIndex)
        }
      })
    },
    /** 更新排序 */
    async updateSortOrder(oldIndex, newIndex) {
      // 如果位置没有变化，则不处理
      if (oldIndex === newIndex) {
        return;
      }

      try {
        // 创建新排序列表
        const sortedList = [...this.labelList];
        
        // 移动元素到新位置
        const [removed] = sortedList.splice(oldIndex, 1);
        sortedList.splice(newIndex, 0, removed);
        
        // 重新计算排序值（倒序，索引越小值越大）
        const updatedList = sortedList.map((item, index) => ({
          ...item,
          sortNum: sortedList.length - index
        }));
        
        // 准备发送到后端的数据 (使用sortNum字段名匹配后端LabelSort模型)
        const sortData = updatedList.map(item => ({
          id: item.id,
          sortNum: item.sortNum
        }));
        
        // 调用排序接口
        await sortLabels(sortData);
        
        // 更新本地数据
        this.labelList = updatedList;
        this.$modal.msgSuccess("排序更新成功");
      } catch (error) {
        this.$modal.msgError("排序更新失败");
        console.error(error);
        // 重新加载数据以确保一致性
        this.getList();
      }
    }
  }
}
</script>

<style scoped>
.sortable-ghost {
  opacity: .8;
  background: #42b983 !important;
}
</style>